package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.DrmoPackageDao;
import mil.af.amc.adpetracker.model.AdpeAccount;
import mil.af.amc.adpetracker.model.DrmoPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;

import java.util.List;

/**
 * Hibernate DAO for DrmoPackageDispatchAction objects
 *
 * @author TSgt Jason Ferguson
 */

public class HibernateDrmoPackageDao extends HibernateGenericDao<DrmoPackage> implements DrmoPackageDao {

    public HibernateDrmoPackageDao() {
        super(DrmoPackage.class);
    }

    public DrmoPackage getByDtid(String dtid) {

        DetachedCriteria crit = DetachedCriteria.forClass(DrmoPackage.class);
        crit.add(Restrictions.ilike("dtid", dtid));

        List<DrmoPackage> results = (List<DrmoPackage>) getHibernateTemplate().findByCriteria(crit);

        if (results.size() > 0) {
            return results.get(0);
        } else {
            return null;
        }
    }

    public List<DrmoPackage> getAllByAdpeAccount(AdpeAccount acct) {

        DetachedCriteria crit = DetachedCriteria.forClass(DrmoPackage.class);
        DetachedCriteria adpeCrit = crit.createCriteria("adpeAccount");
        adpeCrit.add(Restrictions.eq("id", acct.getId()));

        return (List<DrmoPackage>) getHibernateTemplate().findByCriteria(crit);
    }

    public List<DrmoPackage> getPendingByAdpeAccount(AdpeAccount acct) {

        DetachedCriteria crit = DetachedCriteria.forClass(DrmoPackage.class);
        DetachedCriteria adpeCrit = crit.createCriteria("adpeAccount");
        adpeCrit.add(Restrictions.eq("id", acct.getId()));

        crit.add(Restrictions.isNull("turninDate"));

        return (List<DrmoPackage>) getHibernateTemplate().findByCriteria(crit);
    }

    public int getPendingCountByAdpeAccount(AdpeAccount acct) {

        DetachedCriteria crit = DetachedCriteria.forClass(DrmoPackage.class);
        DetachedCriteria adpeCrit = crit.createCriteria("adpeAccount");
        adpeCrit.add(Restrictions.eq("id", acct.getId()));

        crit.setProjection(Projections.rowCount());

        return (Integer) getHibernateTemplate().findByCriteria(crit).get(0);
    }
}
